package com.mby.utils;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by noah on 2018/4/19.
 */
@Component
public class CorsFilter implements Filter {
    private String[] excludePaths;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //不能在初始化中通过Appliaction Context获取因为这时候还没初始化Application Context
        //baseUserService = SpringUtils.getBean("baseUserService", BaseUserService.class);
        //excludePaths = new String[]{"/api/user/noLogin", "/api/user/tokenError", "/api/user/loginForeground","/api/user/loginBackground", "/api/user/inCorrectUserId"};
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String origin = "*";
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        /*if(httpServletRequest.getHeader("origin") != null){
            origin = httpServletRequest.getHeader("origin");
        }
        //这里填写你允许进行跨域的主机ip
        httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);*/
        //允许的访问方法
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        //Access-Control-Max-Age 用于 CORS 相关配置的缓存
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        //httpServletResponse.setHeader("Access-Control-Allow-Credentials","true");
        chain.doFilter(request, response);
        /*String userId = request.getParameter("userId");
        String token = request.getParameter("token");
        //有token的                                                     `
        if (userId != null && token != null) {
            try {
                Integer id = Integer.parseInt(userId);
                if (baseUserService == null)
                    baseUserService = SpringUtils.getBean("baseUserService", BaseUserService.class);
                int status = baseUserService.checkLogin(id, token);
                if (status == 1) {
                    chain.doFilter(request, response);
                } else if (status == 0) {
                    httpServletResponse.sendRedirect("/api/user/tokenError");
                } else if (status == -2) {
                    httpServletResponse.sendRedirect("/api/user/inCorrectUserId");
                } else {
                    httpServletResponse.sendRedirect("/api/user/noLogin");
                }
            } catch (NumberFormatException exception) {
                httpServletResponse.sendRedirect("/api/user/inCorrectUserId");
            }
        } else {
            String path = httpServletRequest.getServletPath();
            if (excludePath(path)) {
                chain.doFilter(request, response);
            } else {
                httpServletRequest.getRequestDispatcher("/api/user/noLogin").forward(request, response);
            }
        }*/
//        ((HttpServletResponse) response).addHeader("Access-Control-Allow-Origin", "*");
//        CorsFilter corsFilter=new CorsFilter();

    }

    private boolean excludePath(String path) {
        for (int i = 0; i < excludePaths.length; i++) {
            if (path.equals(excludePaths[i])) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {
        System.out.println("destroy method");
    }

}